// 获取渠道的数据
import React, { useState, useEffect } from 'react';
import { Select } from 'antd';

import { compare } from 'src/utils/compare';
import services from '../services/api';
export default function useAppProductEventData(props) {
  const {
    app_id,
    product_id,
    event_id,
    event_name,
    isImportant,
    layout,
    disabled,
    form,
    hideLabel,
    app_placeholder,
    isAddAll,
    product_placeholder,
    event_placeholder,
    onAppChange = () => {},
    onProductChange = () => {},
    onEventChange = () => {},
  } = props;
  const [applications, setApplications] = useState([]);
  const [products, setProducts] = useState([]);
  const [events, setEvents] = useState([]);
  const [appId, setAppId] = useState(app_id);
  const [productId, setProductId] = useState(product_id);
  const [eventId, setEventId] = useState(event_id);
  const [productToEvent, setProductToEvent] = useState(false); // false表示event回填product，因为event回填porduct是异步，所以event修改回调里会获取到之前的product_id

  useEffect(() => {
    app_id && setAppId(app_id);
  }, [app_id]);
  useEffect(() => {
    product_id && setProductId(product_id);
  }, [product_id]);
  useEffect(() => {
    event_id && setEventId(event_id);
  }, [event_id]);

  useEffect(() => {
    getApp({});
    getAllProductCodeList({});
  }, []);

  useEffect(() => {
    app_id && getEvents({ app_id, product_id });
  }, [app_id, product_id]);

  // 获取渠道
  function getApp() {
    services.application.getAppCodeList({}).then((res) => {
      if (res.code === 0) {
        if (isAddAll) {
          res.data.unshift({ app_id: -1, app_name: '所有渠道' });
        }
        setApplications(res.data);
      }
    });
  }

  // 获取事件
  function getEvents({ app_id, product_id }) {
    const params = {};
    if (app_id) {
      params.app_id = app_id;
    }
    if (product_id) {
      params.product_id = product_id;
    }
    services.event.getEventCodeList(params).then((res) => {
      if (res.code === 0) {
        setEvents(res.data);
      }
    });
  }

  // 获取产品
  function getAllProductCodeList({ app_id, event_id }) {
    services.product.getProductCodeList(event_id ? { app_id, event_id } : {}).then((res) => {
      if (res.code === 0) {
        setProducts(res.data);
        // 当event_id存在，默认回写productId
        if (event_id) {
          const p_id = res.data.length === 1 ? res.data[0].product_id : undefined;
          setProductId(p_id);
          form && form.setFieldsValue({ product_id: p_id });
        }
      }
    });
  }

  // 改变app,则清空事件id
  function appChangeHandle(id) {
    setAppId(id);
    getEvents({ app_id: id, product_id: productId });
    clearEvent();
    window.setTimeout(() => {
      onAppChange && onAppChange(id);
    }, 0);
  }
  // 改变product,
  function productChangeHandle(id) {
    setProductToEvent(true);
    setProductId(id);
    if (!id) {
      getAllProductCodeList({});
      setProductToEvent(false);
    }
    getEvents({ app_id: appId, product_id: id });
    clearEvent();
    window.setTimeout(() => {
      onProductChange && onProductChange(id);
    }, 0);
  }

  // 改变event,
  function eventChangeHandle(id) {
    if (!productToEvent) {
      setProductId(undefined);
      form && form.setFieldsValue({ product_id: undefined });
      getAllProductCodeList({ app_id: appId, event_id: id });
    }
    setEventId(id);
    window.setTimeout(() => {
      onEventChange && onEventChange(id);
    }, 0);
  }
  // 清空事件
  function clearEvent() {
    setEventId(undefined);
    form && form.setFieldsValue({ event_id: undefined }); // 清空event
  }

  return {
    applications,
    events,
    products,
    appId,
    productId,
    eventId,
    items: [
      {
        label:
          (!hideLabel && {
            label: '所属渠道',
            ...layout,
          }) ||
          '',
        name: 'app_id',
        options: {
          initialValue: app_id,
          rules: [{ required: true, message: '请选择渠道' }],
        },
        component: (
          <Select
            style={{ width: '100%', ...compare(props, 'app_id') }}
            onChange={(value) => appChangeHandle(value)}
            placeholder={app_placeholder || '请选择'}
            disabled={disabled}
          >
            {applications
              .filter((it) => isAddAll || it.app_id !== -1)
              .map((it) => {
                return (
                  <Select.Option value={it.app_id} key={it.app_id}>
                    {it.app_name}
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
      {
        label:
          (!hideLabel && {
            label: '关联产品',
            ...layout,
          }) ||
          '',
        name: 'product_id',
        options: {
          initialValue: product_id || undefined,
        },
        component: (
          <Select
            style={{ width: '100%', ...compare(props, 'product_id') }}
            placeholder={product_placeholder || '请选择'}
            onChange={(value) => productChangeHandle(value)}
            disabled={disabled}
            allowClear
          >
            {products
              .filter((it) => it.product_id !== -1)
              .map((it) => {
                return (
                  <Select.Option value={it.product_id} key={it.product_id}>
                    {it.product_name}
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
      {
        label:
          (!hideLabel && {
            label: '关联事件',
            ...layout,
          }) ||
          '',
        name: 'event_id',
        options: {
          initialValue: isImportant ? event_name : event_id,
          rules: isAddAll ? [] : [{ required: true, message: '请选择关联事件' }],
        },
        component: (
          <Select
            style={{ width: '100%', ...compare(props, 'event_id') }}
            placeholder={event_placeholder || '请选择'}
            onChange={(value) => eventChangeHandle(value)}
            allowClear={isAddAll}
            disabled={disabled}
          >
            {events
              .filter((it) => it.event_id !== -1)
              .map((it) => {
                return (
                  <Select.Option value={it.event_id} key={it.event_id}>
                    {it.event_name}
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
    ],
  };
}
